﻿// YS.K12

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace YS.Domain.IoT.Option;
/// <summary>
/// 获取Appsettings配置信息
/// </summary>
public class AppSettingsHelper
{
    private static IConfiguration Configuration { get; set; }

    // 静态构造函数会在类的任何成员第一次被访问之前执行
    static AppSettingsHelper()
    {
        Initialize();
    }
    private static void Initialize()
    {
        var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
        var path =Path.Combine(Directory.GetCurrentDirectory(), "Configuration");
        var builder = new ConfigurationBuilder()
            .SetBasePath(path)
            //.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true);
        //.AddJsonFile($"appsettings.Staging.json", optional: true, reloadOnChange: true);
        Console.WriteLine($"程序配置文件读取路径:{path}");
        Configuration = builder.Build();
    }

    /// <summary>
    /// 获取配置项内容
    /// </summary>
    /// <param name="sections">节点配置</param>
    /// <returns>配置项值</returns>
    public static string GetContent(params string[] sections)
    {
        if (sections.Any())
        {
            return Configuration[string.Join(":", sections)];
        }
        return "";
    }

    /// <summary>
    /// 设置配置项内容到指定文件中（注意：这会覆盖原有文件）
    /// </summary>
    /// <param name="value">要设置的值</param>
    /// <param name="sections">节点配置</param>
    /// <returns>是否成功设置</returns>
    public static bool SetContent(string value, params string[] sections)
    {
        try
        {
            // 注意: 修改配置文件的行为在生产环境中是不推荐的。
            // 更好的做法是通过部署过程或者环境变量来更改配置。
            string contentPath = AppDomain.CurrentDomain.BaseDirectory;
            string path = Path.Combine(contentPath, "appsettings.json");

            JObject jsonObject;
            using (StreamReader file = new StreamReader(path))
            using (JsonTextReader reader = new JsonTextReader(file))
            {
                jsonObject = (JObject)JToken.ReadFrom(reader);
                JToken token = jsonObject;
                foreach (var section in sections.Take(sections.Length - 1))
                {
                    token = token[section];
                }
                token[sections.Last()] = value;
            }

            using (var writer = new StreamWriter(path))
            using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
            {
                jsonObject.WriteTo(jsonWriter);
            }
        }
        catch (Exception)
        {
            return false;
        }

        return true;
    }


}
